package com.front.web.wx.utils;

import java.io.Writer;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bootdo.wx.domain.Message;
import com.bootdo.wx.service.MessageService;
import com.front.web.wx.model.NewS;
import com.front.web.wx.model.WechatImgMsg;
import com.front.web.wx.model.WechatTextMsg;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;

@Service
public class MessageUtils {
	
	@Autowired
	private MessageService messageService;
	
	
   //定义微信消息类型--文本
   public static final String TEXT_MSG_TYPE = "text";
 //定义微信消息类型--图片
   public static final String IMG_MSG_TYPE = "image";
   //语音
   public static final String VOICE_MSG_TYPE = "voice";
   //事件
   public static final String EVENT_MSG_TYPE = "event";
	/**
     * 处理微信信息
     * @param reqInfo xml信息数据
     * @return 处理结果
     */
    public  String dealWechatMsg(String reqInfo)
    {
        String ret = reqInfo;
        String result = "";
        try
        {
            Document returndoc = DocumentHelper.parseText(ret);
            Element rootElement = returndoc.getRootElement();
            String tMsgType = rootElement.elementText("MsgType");
            String openId = rootElement.elementText("FromUserName");
            String fromId = rootElement.elementText("ToUserName");
            
            String parText = null;
            
            if(TEXT_MSG_TYPE.equals(tMsgType)) {
            	parText = rootElement.elementText("Content");
            	//return createTextMessag(openId,fromId , "hi,您刚才发送的是"+rootElement.elementText("Content"));
            }
            if(VOICE_MSG_TYPE.equals(tMsgType)) {
            	parText = rootElement.elementText("Recognition");
            	if(parText.charAt(parText.length()-1) == '。' && parText.length() > 2) {
            		parText = parText.substring(0, parText.length()-1);
            	}
            	//return createTextMessag(openId,fromId , "hi,您刚才语音说的是"+parText);
            }
            
            Map map = new HashMap();
            map.put("keyword", parText);
            List<Message>  mesL = messageService.list(map);
            if(null != mesL && mesL.size() > 0) {
            	for(int i = 0; i < mesL.size(); i++) {
            		if(mesL.get(i).getType().equals(2)) {
            			return createImgMessag(openId,fromId , mesL.get(i).getRemark());
            		}else if (mesL.get(i).getType().equals(1)){
            			return createTextMessag(openId,fromId , mesL.get(i).getText());
            		}else if (mesL.get(i).getType().equals(3)) {
            			return  createTuwenXiaoxi(openId,fromId ,mesL.get(i));
            		}
            	}
            }
            
            
            
            if(EVENT_MSG_TYPE.equals(tMsgType)) {
            	String event = rootElement.elementText("Event");
             	if("subscribe".equals(event)) {
             		return createTextMessag(openId,fromId , "hi,欢迎您关注我的公众号哦");
             	}else if("unsubscribe".equals(event)) {
             		return createTextMessag(openId,fromId , "客官不要走 ~");
             	}
            }
        }
        catch (DocumentException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return result;
    }
   
    
    
    private  String  createTextMessag(String openId,
    		String fromId,String text) {
    	WechatTextMsg tReturnMsg = new WechatTextMsg();
    	 // 封装返回信息
        tReturnMsg.setCreateTime(new Date().getTime() + "");
        tReturnMsg.setToUserName(openId);
        tReturnMsg.setFromUserName(fromId);
        tReturnMsg.setContent(text);
        tReturnMsg.setMsgType(TEXT_MSG_TYPE);
        // 将返回结果封装成文本消息
    	return obj2XML(tReturnMsg);
    }
    
    
    private String  createTuwenXiaoxi(String openId,
    		String fromId,Message message) {
    	String str = "<xml><ToUserName><![CDATA["+openId+"]]></ToUserName>"
    			+ "<FromUserName><![CDATA["+fromId+"]]></FromUserName>"
    			+"<CreateTime>"+System.currentTimeMillis()+"</CreateTime>"
    			+"<MsgType><![CDATA[news]]></MsgType>"
    			+"<ArticleCount>1</ArticleCount>"
    			+"<Articles><item><Title><![CDATA["+message.getTitle()+"]]></Title>"
    			+"<Description><![CDATA["+message.getDescription()+"]]></Description>"
    			+"<PicUrl><![CDATA["+message.getPicUrl()+"]]></PicUrl>"
    			+"<Url><![CDATA["+message.getUrl()+"]]></Url></item></Articles></xml>";
    	return str;
    }
    
    
    private  String  createImgMessag(String openId,
    		String fromId,String mediaId) {
    	WechatImgMsg tReturnMsg = new WechatImgMsg();
    	 // 封装返回信息
        tReturnMsg.setCreateTime(new Date().getTime() + "");
        tReturnMsg.setToUserName(openId);
        tReturnMsg.setFromUserName(fromId);
        tReturnMsg.setImage(mediaId);
        tReturnMsg.setMsgType(IMG_MSG_TYPE);
        // 将返回结果封装成文本消息
    	return obj2XML(tReturnMsg);
    }
    
    
    /**
             * 将对象转为XML输出
     * @param textMsg
     * @return
     */
    private  String obj2XML(Object obj)
    {
        xstream.alias("xml", obj.getClass());
        xstream.autodetectAnnotations(true);
        return xstream.toXML(obj);

    }

    
    /**
          * 扩展xstream使其支持CDATA
     */
    private  XStream xstream = new XStream(new XppDriver()
    {
        public HierarchicalStreamWriter createWriter(Writer out)
        {
            return new PrettyPrintWriter(out)
            {
                // 对所有xml节点的转换都增加CDATA标记
                boolean cdata = true;
                
                boolean isImg = false;

                @SuppressWarnings("unchecked")
                public void startNode(String name, Class clazz)
                {	
                    if(name.equals("CreateTime")) {
                    	cdata = false;
                    }else {
                    	cdata = true;
                    }
                    
                    
                    if(name.equals("Image")) {
                    	isImg = true;
                    }else {
                    	isImg = false;
                    }
                    
                	super.startNode(name, clazz);
                }

                protected void writeText(QuickWriter writer, String text)
                {
                    if (cdata)
                    {
                    	if(isImg) {
                    		 writer.write("<MediaId>");
                    		 writer.write("<![CDATA[");
                             writer.write(text);
                             writer.write("]]>");
                             writer.write("</MediaId>");
                    	}else {
                    		 writer.write("<![CDATA[");
                             writer.write(text);
                             writer.write("]]>");
                    	}
                       
                    }
                    else
                    {
                        writer.write(text);
                    }
                }
            };
        }
    });
    
}
